using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using HtmlParsing.Tegs;

namespace HtmlParsing
{
  public class HtmlDocParser
  {
    public static Hashtable GetFormTegs(string content)
    {
      Hashtable res = new Hashtable();

      string pattern = @"<[\f\n\r\t\v]*form[^>]*>";
      Regex re = new Regex(pattern);
      MatchCollection ms = re.Matches(content);
      if (ms.Count <= 0)
        return null;

      foreach (Match m in ms)
      {
        TegForm form = new TegForm(m.Value);

        int startAt = m.Index + m.Length;
        form.OpenTeg = m.Value;
        SetInnerTextAndContent(form, content, startAt);

        string key = form.Name == null || form.Name.Trim() == String.Empty 
                                  ? Guid.NewGuid().ToString() : form.Name;
        res.Add(key.ToUpper(), form);
      }
      return res;
    }

    public static void SetInnerTextAndContent(TegForm form, string content, int startAt)
    {
      string pattern = @"<[\f\n\r\t\v]*/[\f\n\r\t\v]*form[\f\n\r\t\v]*>";
      Regex re = new Regex(pattern);
      Match m = re.Match(content, startAt);
      if (m == null)
        return;
      form.TegInnerText = content.Substring(startAt, m.Index - startAt);
      form.CloseTeg = m.Value;
    }


    public static string GetSearchContent(string content, string pattern)
    {
      string lowContent = content.ToLower();

      Regex re = new Regex(pattern);

      MatchCollection ms = re.Matches(lowContent);
      if (ms.Count <= 0)
        return null;

      string tegString = content.Substring(ms[0].Index, ms[0].Length);

      return tegString;
    }

    public static string GetInputValue(string content, string pattern)
    {
      string tegString = GetSearchContent(content, pattern);
      TegInput teg = new TegInput(tegString);
      return teg.Value;
    }

    public static string GetAHref(string content, string pattern)
    {
      string tegString = GetSearchContent(content, pattern);
      TegA teg = new TegA(tegString);
      return teg.Href;
    }

  }
}
